from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect, reverse
import string
from django.http.response import JsonResponse

# from .models import CaptchaModel, UserActivity
# from .forms import RegisterForm,LoginForm,PubBlogForm
# from .models import BlogCategory, Blog,BlogComment
# Create your views here.
import random
from django.core.mail import send_mail
from django.views.decorators.http import require_http_methods, require_POST, require_GET

from django.contrib.auth import get_user_model, login, logout
from django.urls.base import reverse_lazy
from django.contrib.auth.decorators import login_required
import json
from django.db.models import Q
import time


def index(request):
    """首页"""
    return render(request, 'game/index.html')


def login_lab(request):
    return render(request, 'game/login.html')


def generate(request):
    return render(request, "Labyrinth_generate.html")


def generate_id(request, user_id):
    return render(request, "Labyrinth_id.html", context={"user_id": user_id})


def generate_id_pro1(request, user_id):
    return render(request, "test.html", context={"user_id": user_id})


import json
import uuid
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.http import require_POST
from .models import Game, Player, GameState, Score

import json
import uuid
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Game, Player, GameState, Score


@csrf_exempt
def save(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)

            # 1. 保存游戏主数据
            game, created = Game.objects.update_or_create(
                game_id=data['game_id'],
                defaults={
                    'maze_data': data['maze_data'],
                    'maze_size': data['maze_size'],
                    'difficulty': data['difficulty'],
                    'game_time': data['game_time'],
                    'best_time': data['best_time'],
                    'is_completed': data['is_completed'],
                    'end_time': data.get('end_time')
                }
            )

            # 2. 保存玩家状态
            for player_data in data['players']:
                Player.objects.update_or_create(
                    player_id=player_data['player_id'],
                    defaults={
                        'game_id': data['game_id'],
                        'player_number': player_data['player_number'],
                        'x_position': player_data['x_position'],
                        'y_position': player_data['y_position'],
                        'color': player_data['color'],
                        'is_completed': player_data['is_completed']
                    }
                )

            # 3. 保存游戏状态
            GameState.objects.update_or_create(
                game_id=data['game_id'],
                defaults={
                    'current_player': data['game_state']['current_player'],
                    'is_solving': data['game_state']['is_solving']
                }
            )

            # 4. 保存玩家分数
            for score_data in data['scores']:
                Score.objects.update_or_create(
                    score_id=score_data.get('score_id', str(uuid.uuid4())),
                    defaults={
                        'game_id': data['game_id'],
                        'player_id': score_data['player_id'],
                        'score': score_data['score'],
                        'completion_time': score_data['completion_time']
                    }
                )

            return JsonResponse({'status': 'success', 'message': 'Game saved successfully'})

        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=400)

    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=405)


import uuid
import json
import random
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Game, Player, GameState


@require_POST
@csrf_exempt
def labyrinth_sql_save(request):
    """
    生成迷宫并保存到数据库的视图
    """
    # 从请求中获取迷宫大小（默认为15）
    maze_size = int(request.POST.get('size', 15))
    maze_gen = str(request.POST.get('maze_gen', 'dfs'))

    # 确定难度级别
    if maze_size <= 15:
        difficulty = 'easy'
    elif maze_size <= 25:
        difficulty = 'medium'
    else:
        difficulty = 'hard'

    # 生成迷宫数据

    if maze_gen == 'dfs':
        maze_data = generate_maze_dfs(maze_size)
    elif maze_gen == 'kill':
        maze_data = generate_maze_hunt_and_kill(maze_size)
    elif maze_gen == 'prim':
        maze_data = generate_maze_prim(maze_size)
    elif maze_gen == 'kruskal':
        maze_data = generate_maze_kruskal(maze_size)
    elif maze_gen == 'division':
        maze_data = generate_maze_recursive_division(maze_size)
    else:
        maze_data = generate_maze_hunt_and_kill(maze_size)

    # 创建新的游戏实例
    game = Game.objects.create(
        maze_data=maze_data,
        maze_size=maze_size,
        difficulty=difficulty,
        is_completed=False
    )

    # 为游戏创建玩家
    players = []
    player_colors = ['#ffeb3b', '#2196F3', '#4CAF50', '#ffffff']
    # 目前启用的是这一段
    for i in range(4):
        player = Player.objects.create(
            game=game,
            player_number=i + 1,
            x_position=1,
            y_position=1,
            color=player_colors[i],
            is_completed=False
        )
        players.append(player)
    # 创建游戏状态
    game_state = GameState.objects.create(
        game=game,
        current_player=1,
        is_solving=False
    )

    # 返回响应
    return JsonResponse({
        'status': 'success',
        'game_id': str(game.game_id),
        'maze_size': maze_size,
        'difficulty': difficulty,
        'players_created': len(players)
    })


@csrf_exempt
def generate_maze(size):
    """
    使用深度优先搜索算法生成迷宫
    """
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 使用深度优先搜索生成迷宫路径
    stack = [(1, 1)]
    maze[1][1] = 0  # 起点

    # 四个方向：上、右、下、左
    directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]

    while stack:
        x, y = stack[-1]
        random.shuffle(directions)
        found = False

        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            # 检查是否在边界内
            if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                # 打通墙壁
                maze[y + dy // 2][x + dx // 2] = 0
                maze[ny][nx] = 0
                stack.append((nx, ny))
                found = True
                break

        if not found:
            stack.pop()

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze


import random
from django.views.decorators.csrf import csrf_exempt


def generate_maze_dfs(size):
    """使用深度优先搜索算法生成迷宫"""
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 使用深度优先搜索生成迷宫路径
    stack = [(1, 1)]
    maze[1][1] = 0  # 起点

    # 四个方向：上、右、下、左
    directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]

    while stack:
        x, y = stack[-1]
        random.shuffle(directions)
        found = False

        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            # 检查是否在边界内
            if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                # 打通墙壁
                maze[y + dy // 2][x + dx // 2] = 0
                maze[ny][nx] = 0
                stack.append((nx, ny))
                found = True
                break

        if not found:
            stack.pop()

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze


def generate_maze_prim(size):
    """使用Prim算法生成迷宫"""
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 从随机点开始
    start_x, start_y = random.randint(1, size - 2) // 2 * 2 + 1, random.randint(1, size - 2) // 2 * 2 + 1
    maze[start_y][start_x] = 0

    # 候选墙列表
    walls = []
    directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]

    # 将起点周围的墙加入列表
    for dx, dy in directions:
        nx, ny = start_x + dx, start_y + dy
        if 0 < nx < size - 1 and 0 < ny < size - 1:
            walls.append((nx, ny))

    while walls:
        # 随机选择一堵墙
        wall_x, wall_y = random.choice(walls)
        walls.remove((wall_x, wall_y))

        # 计算墙两侧的单元格
        if wall_x % 2 == 0:  # 垂直墙
            cell1_x, cell1_y = wall_x - 1, wall_y
            cell2_x, cell2_y = wall_x + 1, wall_y
        else:  # 水平墙
            cell1_x, cell1_y = wall_x, wall_y - 1
            cell2_x, cell2_y = wall_x, wall_y + 1

        # 检查是否一个单元格已访问而另一个未访问
        if (0 < cell1_x < size - 1 and 0 < cell1_y < size - 1 and
                0 < cell2_x < size - 1 and 0 < cell2_y < size - 1):
            if (maze[cell1_y][cell1_x] == 0 and maze[cell2_y][cell2_x] == 1) or \
                    (maze[cell1_y][cell1_x] == 1 and maze[cell2_y][cell2_x] == 0):
                # 打通墙壁
                maze[wall_y][wall_x] = 0

                # 将未访问的单元格标记为已访问，并添加其周围的墙
                if maze[cell1_y][cell1_x] == 1:
                    maze[cell1_y][cell1_x] = 0
                    for dx, dy in directions:
                        nx, ny = cell1_x + dx, cell1_y + dy
                        if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                            walls.append((nx, ny))
                else:
                    maze[cell2_y][cell2_x] = 0
                    for dx, dy in directions:
                        nx, ny = cell2_x + dx, cell2_y + dy
                        if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                            walls.append((nx, ny))

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze


def generate_maze_kruskal(size):
    """使用Kruskal算法生成迷宫"""
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 创建单元格集合，每个单元格初始时属于自己的集合
    sets = {}
    for y in range(1, size - 1, 2):
        for x in range(1, size - 1, 2):
            maze[y][x] = 0
            sets[(x, y)] = (x, y)

    # 创建所有可能的墙
    walls = []
    for y in range(1, size - 1, 2):
        for x in range(1, size - 1, 2):
            # 右墙
            if x + 2 < size - 1:
                walls.append(((x, y), (x + 2, y)))
            # 下墙
            if y + 2 < size - 1:
                walls.append(((x, y), (x, y + 2)))

    # 随机打乱墙的顺序
    random.shuffle(walls)

    # 查找单元格所属的集合
    def find(cell):
        if sets[cell] != cell:
            sets[cell] = find(sets[cell])
        return sets[cell]

    # 合并两个集合
    def union(cell1, cell2):
        root1 = find(cell1)
        root2 = find(cell2)
        if root1 != root2:
            sets[root2] = root1
            return True
        return False

    # 处理每堵墙
    for (cell1_x, cell1_y), (cell2_x, cell2_y) in walls:
        if union((cell1_x, cell1_y), (cell2_x, cell2_y)):
            # 打通墙壁
            wall_x, wall_y = (cell1_x + cell2_x) // 2, (cell1_y + cell2_y) // 2
            maze[wall_y][wall_x] = 0

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze


def generate_maze_recursive_division(size):
    """使用递归分割算法生成迷宫"""
    # 初始化迷宫（全部为通路）
    maze = [[0 for _ in range(size)] for _ in range(size)]

    # 在迷宫周围添加墙
    for i in range(size):
        maze[0][i] = 1
        maze[size - 1][i] = 1
        maze[i][0] = 1
        maze[i][size - 1] = 1

    # 递归分割函数
    def divide(x1, y1, x2, y2):
        width = x2 - x1
        height = y2 - y1

        # 如果区域太小，不再分割
        if width < 3 or height < 3:
            return

        # 决定是水平分割还是垂直分割
        if width > height:
            vertical = True
        elif height > width:
            vertical = False
        else:
            vertical = random.choice([True, False])

        if vertical:
            # 选择一个偶数位置放置墙
            wall_x = random.randrange(x1 + 2, x2, 2)

            # 选择一个奇数位置作为门
            door_y = random.randrange(y1 + 1, y2, 2)

            # 放置墙
            for y in range(y1, y2 + 1):
                if y != door_y:
                    maze[y][wall_x] = 1

            # 递归分割左右两部分
            divide(x1, y1, wall_x - 1, y2)
            divide(wall_x + 1, y1, x2, y2)
        else:
            # 选择一个偶数位置放置墙
            wall_y = random.randrange(y1 + 2, y2, 2)

            # 选择一个奇数位置作为门
            door_x = random.randrange(x1 + 1, x2, 2)

            # 放置墙
            for x in range(x1, x2 + 1):
                if x != door_x:
                    maze[wall_y][x] = 1

            # 递归分割上下两部分
            divide(x1, y1, x2, wall_y - 1)
            divide(x1, wall_y + 1, x2, y2)

    # 开始递归分割
    divide(1, 1, size - 2, size - 2)

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze


def generate_maze_hunt_and_kill(size):
    """使用狩猎与杀戮算法生成迷宫"""
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]
    # 从随机点开始
    start_x, start_y = random.randint(1, size - 2) // 2 * 2 + 1, random.randint(1, size - 2) // 2 * 2 + 1
    maze[start_y][start_x] = 0
    # 当前单元格
    current_x, current_y = start_x, start_y
    # 四个方向：上、右、下、左
    directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]
    # 杀戮阶段
    while True:
        # 寻找未访问的相邻单元格
        random.shuffle(directions)
        found = False

        for dx, dy in directions:
            nx, ny = current_x + dx, current_y + dy
            if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                # 打通墙壁
                maze[current_y + dy // 2][current_x + dx // 2] = 0
                maze[ny][nx] = 0

                # 移动到新单元格
                current_x, current_y = nx, ny
                found = True
                break
        # 如果找不到未访问的相邻单元格，进入狩猎阶段
        if not found:
            # 狩猎阶段
            hunted = False
            for y in range(1, size - 1, 2):
                if hunted:
                    break
                for x in range(1, size - 1, 2):
                    if maze[y][x] == 0:
                        # 检查是否有未访问的相邻单元格
                        for dx, dy in directions:
                            nx, ny = x + dx, y + dy
                            if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                                # 打通墙壁
                                maze[y + dy // 2][x + dx // 2] = 0
                                maze[ny][nx] = 0

                                # 移动到新单元格
                                current_x, current_y = nx, ny
                                hunted = True
                                break
                    if hunted:
                        break

            # 如果找不到可连接的单元格，算法结束
            if not hunted:
                break

    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点
    return maze

def generate_maze_eller(size):
    """使用Eller算法生成迷宫"""
    # 初始化迷宫（全部为墙）
    maze = [[1 for _ in range(size)] for _ in range(size)]

    # 创建单元格集合
    sets = {}
    for x in range(1, size - 1, 2):
        sets[x] = x
    # 处理每一行
    for y in range(1, size - 1, 2):
        # 随机决定是否打通右侧墙壁
        for x in range(1, size - 3, 2):
            # 如果右侧单元格属于不同集合，则有50%概率打通
            if sets[x] != sets[x + 2] and random.random() < 0.5:
                # 打通右侧墙壁
                maze[y][x + 1] = 0

                # 合并集合
                old_set = sets[x + 2]
                for cell in sets:
                    if sets[cell] == old_set:
                        sets[cell] = sets[x]
        # 处理下一行的连接
        if y < size - 3:
            # 为每个集合创建至少一个向下的连接
            set_members = {}
            for x in sets:
                if sets[x] not in set_members:
                    set_members[sets[x]] = []
                set_members[sets[x]].append(x)

            for set_id in set_members:
                # 至少有一个向下的连接
                connected = False
                for x in set_members[set_id]:
                    if random.random() < 0.7 or not connected:  # 70%概率创建连接，确保每个集合至少有一个
                        # 打通下方墙壁
                        maze[y + 1][x] = 0
                        connected = True

                # 为下一行创建新的集合
                for x in set_members[set_id]:
                    if maze[y + 1][x] == 0:
                        sets[x] = x  # 新集合
    # 设置起点和终点
    maze[1][1] = 2  # 起点
    maze[size - 2][size - 2] = 3  # 终点

    return maze

def labyrinth_future_sql_save(request):
    """
    现有迷宫并保存到数据库的视图
    """
    # < QueryDict: {'size': ['15'], 'game_data': [
    #     '{"maze_size":15,"maze_data":[[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    #     [1,2,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,1,0,0,0,0,0,1,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,0,0,1,0,0,0,0,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],[1,0,0,0,1,0,1,0,0,0,1,0,0,0,1],
    #     [1,0,0,0,1,0,1,0,0,0,1,0,0,3,1],[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]],
    #     "difficulty":"简单","start_time":"2025-06-22 10:56:28",
    #     "best_time":0,"current_player":1,
    #     "players":
    #     [{"id":1,"x":1,"y":1,"color":"#ffeb3b","completed":false},
    #     {"id":2,"x":1,"y":1,"color":"#2196F3","completed":false},
    #     {"id":3,"x":1,"y":1,"color":"#4CAF50","completed":false},
    #     {"id":4,"x":1,"y":1,"color":"#ffffff","completed":false}],
    #     "start_positions":[[1,1]],"end_position":[13,13]}']} >
    # <
    #
    # class 'django.http.request.QueryDict'>
    if request.method == 'POST':
        try:
            # 从QueryDict获取数据
            game_data_str = request.POST.get('game_data')
            # 解析JSON数据
            game_data = json.loads(game_data_str)
            # 准备Game数据
            difficulty_mapping = {
                '简单': 'easy',
                '中等': 'medium',
                '困难': 'hard'
            }
            difficulty = difficulty_mapping.get(game_data.get('difficulty', '简单'), 'easy')
            # 创建Game记录
            game = Game.objects.create(
                maze_data=game_data.get('maze_data'),
                maze_size=game_data.get('maze_size', 15),
                difficulty=difficulty,
                start_time=game_data.get('start_time'),
                best_time=game_data.get('best_time', 0),
                is_completed=all(player.get('completed', False) for player in game_data.get('players', []))
            )
            # 创建Player记录
            for player_data in game_data.get('players', []):
                print(type(player_data.get('id')))
                Player.objects.create(
                    game=game,
                    player_number=player_data.get('id'),
                    x_position=player_data.get('x', 1),
                    y_position=player_data.get('y', 1),
                    color=player_data.get('color', '#ffeb3b'),
                    is_completed=player_data.get('completed', False)
                )
            # 创建GameState记录
            GameState.objects.create(
                game=game,
                current_player=game_data.get('current_player', 1)
            )
            print('执行原始保留')
            return JsonResponse({
                'status': 'success',
                'message': '游戏数据保存成功',
                'game_id': str(game.game_id),
                'maze_size': game.maze_size,
                'difficulty': game.get_difficulty_display(),
                'players_created': len(game_data.get('players', []))
            })
        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': f'保存游戏数据失败: {str(e)}'
            }, status=500)
    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)

def labyrinth_sql_save_common(request, play_id):
    """
    现有迷宫并保存到数据库的视图
    """
    if request.method == 'POST':
        # 从QueryDict获取数据
        game_data_str = request.POST.get('game_data')
        # 解析JSON数据
        game_data = json.loads(game_data_str)
        # 准备Game数据
        game = Game.objects.latest('start_time')
        # 创建Player记录
        player_data = game_data.get('players', [])[int(play_id) - 1]
        Player.objects.filter(game_id=game.game_id, player_number=play_id).update(
            game=game,
            player_number=player_data.get('id'),
            x_position=player_data.get('x', 1),
            y_position=player_data.get('y', 1),
            color=player_data.get('color', '#ffeb3b'),
            is_completed=player_data.get('completed', False)
        )

        GameState.objects.filter(game=game).update(
            game=game,
            current_player=game_data.get('current_player', 1)
        )

        return JsonResponse({
            'status': 'success',
            'message': '游戏数据保存成功',
            'game_id': str(game.game_id),
            'maze_size': game.maze_size,
            'difficulty': game.get_difficulty_display(),
            'players_created': len(game_data.get('players', []))
        })
    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)


def labyrinth_future_sql_save1(request):
    """
    现有迷宫并保存到数据库的视图
    """
    if request.method == 'POST':
        # 从QueryDict获取数据
        game_data_str = request.POST.get('game_data')
        # 解析JSON数据
        game_data = json.loads(game_data_str)
        # 准备Game数据
        game = Game.objects.latest('start_time')
        # 创建Player记录
        player_data = game_data.get('players', [])[0]
        Player.objects.filter(game_id=game.game_id, player_number=1).update(
            game=game,
            player_number=player_data.get('id'),
            x_position=player_data.get('x', 1),
            y_position=player_data.get('y', 1),
            color=player_data.get('color', '#ffeb3b'),
            is_completed=player_data.get('completed', False)
        )
        # 创建GameState记录
        GameState.objects.create(
            game=game,
            current_player=game_data.get('current_player', 1)
        )
        return JsonResponse({
            'status': 'success',
            'message': '游戏数据保存成功',
            'game_id': str(game.game_id),
            'maze_size': game.maze_size,
            'difficulty': game.get_difficulty_display(),
            'players_created': len(game_data.get('players', []))
        })
    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)

def labyrinth_future_sql_save2(request):
    """
    现有迷宫并保存到数据库的视图
    """
    if request.method == 'POST':
        # 从QueryDict获取数据
        game_data_str = request.POST.get('game_data')
        # 解析JSON数据
        game_data = json.loads(game_data_str)
        # 准备Game数据
        game = Game.objects.latest('start_time')
        # 创建Player记录
        player_data = game_data.get('players', [])[1]
        Player.objects.filter(game_id=game.game_id, player_number=2).update(
            game=game,
            player_number=player_data.get('id'),
            x_position=player_data.get('x', 1),
            y_position=player_data.get('y', 1),
            color=player_data.get('color', '#ffeb3b'),
            is_completed=player_data.get('completed', False)
        )
        # 创建GameState记录
        GameState.objects.create(
            game=game,
            current_player=game_data.get('current_player', 1)
        )
        return JsonResponse({
            'status': 'success',
            'message': '游戏数据保存成功',
            'game_id': str(game.game_id),
            'maze_size': game.maze_size,
            'difficulty': game.get_difficulty_display(),
            'players_created': len(game_data.get('players', []))
        })
    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)


def labyrinth_future_sql_save3(request):
    """
    现有迷宫并保存到数据库的视图
    """
    if request.method == 'POST':
        # 从QueryDict获取数据
        game_data_str = request.POST.get('game_data')
        # 解析JSON数据
        game_data = json.loads(game_data_str)
        # 准备Game数据
        game = Game.objects.latest('start_time')

        # 创建Player记录
        player_data = game_data.get('players', [])[2]

        Player.objects.filter(game_id=game.game_id, player_number=3).update(
            game=game,
            player_number=player_data.get('id'),
            x_position=player_data.get('x', 1),
            y_position=player_data.get('y', 1),
            color=player_data.get('color', '#ffeb3b'),
            is_completed=player_data.get('completed', False)
        )

        # 创建GameState记录
        GameState.objects.create(
            game=game,
            current_player=game_data.get('current_player', 1)
        )

        return JsonResponse({
            'status': 'success',
            'message': '游戏数据保存成功',
            'game_id': str(game.game_id),
            'maze_size': game.maze_size,
            'difficulty': game.get_difficulty_display(),
            'players_created': len(game_data.get('players', []))
        })

    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)

def labyrinth_future_sql_save4(request):
    """
    现有迷宫并保存到数据库的视图
    """
    if request.method == 'POST':
        # 从QueryDict获取数据
        game_data_str = request.POST.get('game_data')
        # 解析JSON数据
        game_data = json.loads(game_data_str)
        # 准备Game数据
        game = Game.objects.latest('start_time')
        # 创建Player记录
        player_data = game_data.get('players', [])[3]
        Player.objects.filter(game_id=game.game_id, player_number=4).update(
            game=game,
            player_number=player_data.get('id'),
            x_position=player_data.get('x', 1),
            y_position=player_data.get('y', 1),
            color=player_data.get('color', '#ffeb3b'),
            is_completed=player_data.get('completed', False)
        )

        # 创建GameState记录
        GameState.objects.create(
            game=game,
            current_player=game_data.get('current_player', 1)
        )

        return JsonResponse({
            'status': 'success',
            'message': '游戏数据保存成功',
            'game_id': str(game.game_id),
            'maze_size': game.maze_size,
            'difficulty': game.get_difficulty_display(),
            'players_created': len(game_data.get('players', []))
        })

    return JsonResponse({
        'status': 'error',
        'message': '只支持POST请求'
    }, status=405)


import json
from django.http import JsonResponse
from django.views.decorators.http import require_GET, require_POST
from .models import Game, Player, GameState
from django.shortcuts import get_object_or_404
from django.db import transaction
import uuid
import random


@require_GET
@csrf_exempt
@csrf_protect
def get_game_data(request):
    """获取指定游戏的完整数据"""
    game_id = request.GET.get('game_id')
    try:
        game = Game.objects.get(game_id=game_id)
        players = Player.objects.filter(game=game)
        game_state = GameState.objects.get(game=game)

        # 准备响应数据
        response_data = {
            'status': 'success',
            'game_id': str(game.game_id),
            'maze_data': game.maze_data,
            'maze_size': game.maze_size,
            'difficulty': game.difficulty,
            'players': [
                {
                    'player_id': str(player.player_id),
                    'player_number': player.player_number,
                    'x_position': player.x_position,
                    'y_position': player.y_position,
                    'color': player.color,
                    'is_completed': player.is_completed
                } for player in players
            ],
            'game_state': {
                'current_player': game_state.current_player,
                'is_solving': game_state.is_solving
            }
        }

        return JsonResponse(response_data)
    except Game.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '游戏不存在'}, status=404)
    except GameState.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '游戏状态不存在'}, status=404)


@require_GET
@csrf_exempt
@csrf_protect
def get_latest_game(request):
    """获取最新的游戏ID"""
    try:
        latest_game = Game.objects.latest('start_time')
        return JsonResponse({
            'status': 'success',
            'game_id': str(latest_game.game_id)
        })
    except Game.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '没有找到游戏'}, status=404)


@require_POST
@csrf_exempt
@csrf_protect
def create_new_game(request):
    """创建新游戏"""
    try:
        data = json.loads(request.body)
        size = int(data.get('size', 15))
        # 确定难度
        if size <= 15:
            difficulty = 'easy'
        elif size <= 25:
            difficulty = 'medium'
        else:
            difficulty = 'hard'

        # 生成迷宫数据 - 使用DFS算法
        def generate_maze(size):
            # 初始化迷宫（全部为墙）
            maze = [[1 for _ in range(size)] for _ in range(size)]
            # 使用深度优先搜索生成迷宫路径
            stack = [(1, 1)]
            maze[1][1] = 0  # 起点
            # 四个方向：上、右、下、左
            directions = [(0, -2), (2, 0), (0, 2), (-2, 0)]
            while stack:
                x, y = stack[-1]
                random.shuffle(directions)
                found = False

                for dx, dy in directions:
                    nx, ny = x + dx, y + dy
                    # 检查是否在边界内
                    if 0 < nx < size - 1 and 0 < ny < size - 1 and maze[ny][nx] == 1:
                        # 打通墙壁
                        maze[y + dy // 2][x + dx // 2] = 0
                        maze[ny][nx] = 0
                        stack.append((nx, ny))
                        found = True
                        break
                if not found:
                    stack.pop()
            # 设置起点和终点
            maze[1][1] = 2  # 起点
            maze[size - 2][size - 2] = 3  # 终点

            return maze

        maze_data = generate_maze(size)
        # 创建新游戏
        with transaction.atomic():
            game = Game.objects.create(
                maze_data=maze_data,
                maze_size=size,
                difficulty=difficulty
            )
            # 创建玩家
            player_colors = ['#ffeb3b', '#2196F3', '#4CAF50', '#9C27B0']
            for i in range(4):
                Player.objects.create(
                    game=game,
                    player_number=i + 1,
                    x_position=1,
                    y_position=1,
                    color=player_colors[i]
                )
            # 创建游戏状态
            GameState.objects.create(
                game=game,
                current_player=1
            )
        return JsonResponse({
            'status': 'success',
            'game_id': str(game.game_id)
        })
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=400)


@require_POST
@csrf_exempt
@csrf_protect
def update_player_position(request):
    """更新玩家位置"""
    try:
        data = json.loads(request.body)
        game_id = data.get('game_id')
        player_id = data.get('player_id')
        x = data.get('x')
        y = data.get('y')
        completed = data.get('completed', False)
        # 获取玩家对象
        player = get_object_or_404(Player, game__game_id=game_id, player_number=player_id)
        # 更新玩家位置
        player.x_position = x
        player.y_position = y
        player.is_completed = completed
        player.save()
        return JsonResponse({'status': 'success'})
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=400)


from django.shortcuts import render
from .models import Game, Player, GameState, Score, Player_position_id1, Player_position_id2, Player_position_id3, \
    Player_position_id4
from django.http import JsonResponse
import json


@csrf_exempt
def get_game_state(request):
    """获取当前游戏状态"""
    try:
        latest_game = Game.objects.latest('start_time')
        game_state = GameState.objects.get(game=latest_game)
        players = Player.objects.filter(game=latest_game).order_by('player_number')

        response_data = {
            'status': 'success',
            'current_player': game_state.current_player,
            'players': [],
            'game_completed': latest_game.is_completed,
            'timestamp': time.time()
        }

        for player in players:
            response_data['players'].append({
                'id': player.player_number,
                'x': player.x_position,
                'y': player.y_position,
                'completed': player.is_completed
            })

        return JsonResponse(response_data)

    except (Game.DoesNotExist, GameState.DoesNotExist):
        return JsonResponse({
            'status': 'error',
            'message': 'No active game found'
        }, status=404)


@csrf_exempt
def move_player(request):
    """处理玩家移动请求"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid method'}, status=405)

    try:
        data = json.loads(request.body)
        player_id = data.get('player_id')
        dx = data.get('dx')
        dy = data.get('dy')

        if player_id is None or dx is None or dy is None:
            return JsonResponse({'status': 'error', 'message': 'Missing parameters'}, status=400)

        with transaction.atomic():
            latest_game = Game.objects.select_for_update().latest('start_time')
            game_state = GameState.objects.select_for_update().get(game=latest_game)

            # 确保当前玩家匹配
            if game_state.current_player != player_id:
                return JsonResponse({
                    'status': 'error',
                    'message': f'It is not player {player_id}\'s turn'
                }, status=400)

            player = Player.objects.get(
                game=latest_game,
                player_number=player_id
            )

            # 获取迷宫数据
            if isinstance(latest_game.maze_data, str):
                maze_data = json.loads(latest_game.maze_data)
            else:
                maze_data = latest_game.maze_data

            # 计算新位置
            new_x = player.x_position + dx
            new_y = player.y_position + dy

            # 检查移动是否有效
            if (0 <= new_x < latest_game.maze_size and
                    0 <= new_y < latest_game.maze_size and
                    maze_data[new_y][new_x] != 1):  # 1代表墙

                # 更新玩家位置
                player.x_position = new_x
                player.y_position = new_y
                player.save()

                # 检查是否到达终点
                if maze_data[new_y][new_x] == 3:  # 3代表终点
                    player.is_completed = True
                    player.save()

                    # 检查所有玩家是否完成
                    players = Player.objects.filter(game=latest_game)
                    all_completed = all(p.is_completed for p in players)

                    if all_completed:
                        latest_game.is_completed = True
                        latest_game.save()
                    else:
                        # 切换到下一个未完成的玩家
                        next_player = Player.objects.filter(
                            game=latest_game,
                            is_completed=False
                        ).exclude(player_number=player_id).order_by('player_number').first()

                        if next_player:
                            game_state.current_player = next_player.player_number
                            game_state.save()

                return JsonResponse({'status': 'success'})
            else:
                return JsonResponse({
                    'status': 'error',
                    'message': 'Invalid move'
                }, status=400)

    except (Game.DoesNotExist, GameState.DoesNotExist, Player.DoesNotExist):
        return JsonResponse({
            'status': 'error',
            'message': 'Game or player not found'
        }, status=404)


@csrf_exempt
def switch_player(request):
    """切换当前玩家"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid method'}, status=405)

    try:
        data = json.loads(request.body)
        player_id = data.get('player_id')

        if player_id is None:
            return JsonResponse({'status': 'error', 'message': 'Missing player ID'}, status=400)

        with transaction.atomic():
            latest_game = Game.objects.select_for_update().latest('start_time')
            game_state = GameState.objects.select_for_update().get(game=latest_game)

            # 检查玩家是否存在
            try:
                player = Player.objects.get(game=latest_game, player_number=player_id)
            except Player.DoesNotExist:
                return JsonResponse({
                    'status': 'error',
                    'message': f'Player {player_id} not found in current game'
                }, status=404)

            # 检查玩家是否已完成
            if player.is_completed:
                return JsonResponse({
                    'status': 'error',
                    'message': f'Player {player_id} has already completed the maze'
                }, status=400)

            # 更新当前玩家
            game_state.current_player = player_id
            game_state.save()

            return JsonResponse({
                'status': 'success',
                'current_player': player_id
            })

    except (Game.DoesNotExist, GameState.DoesNotExist):
        return JsonResponse({
            'status': 'error',
            'message': 'No active game found'
        }, status=404)


@csrf_exempt
def reset_players(request):
    """重置玩家位置"""
    if request.method != 'POST':
        return JsonResponse({'status': 'error', 'message': 'Invalid method'}, status=405)
    try:
        with transaction.atomic():
            latest_game = Game.objects.select_for_update().latest('start_time')
            players = Player.objects.filter(game=latest_game)

            # 获取迷宫数据
            if isinstance(latest_game.maze_data, str):
                maze_data = json.loads(latest_game.maze_data)
            else:
                maze_data = latest_game.maze_data

            # 查找所有起点位置
            start_positions = []
            for y in range(len(maze_data)):
                for x in range(len(maze_data[y])):
                    if maze_data[y][x] == 2:  # 起点
                        start_positions.append((x, y))

            if not start_positions:
                start_positions = [(1, 1)]  # 默认起点

            # 重置每个玩家的位置
            for i, player in enumerate(players):
                # 循环使用起点位置
                start_pos = start_positions[i % len(start_positions)]
                player.x_position = start_pos[0]
                player.y_position = start_pos[1]
                player.is_completed = False
                player.save()

            # 重置游戏状态
            latest_game.is_completed = False
            latest_game.save()

            # 重置当前玩家
            game_state = GameState.objects.get(game=latest_game)
            game_state.current_player = players[0].player_number
            game_state.save()

            return JsonResponse({
                'status': 'success',
                'message': 'Players reset to start positions'
            })
    except (Game.DoesNotExist, GameState.DoesNotExist):
        return JsonResponse({
            'status': 'error',
            'message': 'No active game found'
        }, status=404)


def play(request, play_id):
    import json
    try:
        # 获取最新的游戏
        latest_game = Game.objects.latest('start_time')
        # 获取最新的游戏状态，确保只返回一个对象
        game_states = GameState.objects.filter(game=latest_game).order_by('-state_id')
        if game_states.exists():
            game_state = game_states.first()
        else:
            # 如果没有游戏状态，创建一个新的
            game_state = GameState.objects.create(
                game=latest_game,
                current_player=1  # 设置默认当前玩家
            )
        # 获取玩家编号为1,2,3,4的玩家
        player_numbers = [1, 2, 3, 4]
        players = Player.objects.filter(game=latest_game, player_number__in=player_numbers).order_by('player_number')
        # 如果某些玩家不存在，创建它们
        existing_numbers = [player.player_number for player in players]
        missing_numbers = [num for num in player_numbers if num not in existing_numbers]

        for num in missing_numbers:
            # 查找起点位置
            start_position = None
            if isinstance(latest_game.maze_data, str):
                maze_data = json.loads(latest_game.maze_data)
            else:
                maze_data = latest_game.maze_data
            for y in range(len(maze_data)):
                for x in range(len(maze_data[y])):
                    if maze_data[y][x] == 2:  # 起点
                        start_position = (x, y)
                        break
                if start_position:
                    break
            # 如果没找到起点，使用默认位置
            if not start_position:
                start_position = (1, 1)
            # 创建缺失的玩家
            Player.objects.create(
                game=latest_game,
                player_number=num,
                x_position=start_position[0],
                y_position=start_position[1],
                color=get_player_color(num),  # 获取玩家颜色的辅助函数
                is_completed=False
            )
        # 重新获取所有玩家
        players = Player.objects.filter(game=latest_game, player_number__in=player_numbers).order_by('player_number')
        # 确保maze_data是二维数组
        if isinstance(latest_game.maze_data, str):
            maze_data = json.loads(latest_game.maze_data)
        else:
            maze_data = latest_game.maze_data
        # 查找起点和终点位置
        start_positions = []
        end_position = None
        for y in range(len(maze_data)):
            for x in range(len(maze_data[y])):
                if maze_data[y][x] == 2:  # 起点
                    start_positions.append((x, y))
                elif maze_data[y][x] == 3:  # 终点
                    end_position = (x, y)
        game_data = {
            'maze_size': latest_game.maze_size,
            'maze_data': maze_data,
            'difficulty': latest_game.get_difficulty_display(),
            'start_time': latest_game.start_time.strftime("%Y-%m-%d %H:%M:%S"),
            'best_time': latest_game.best_time,
            'current_player': game_state.current_player,
            'players': [],
            'start_positions': start_positions,
            'end_position': end_position
        }

        for player in players:
            game_data['players'].append({
                'id': player.player_number,
                'x': player.x_position,
                'y': player.y_position,
                'color': player.color,
                'completed': player.is_completed
            })

        return render(request, 'plays/play.html', {
            "play_id": play_id,
            'game_data': json.dumps(game_data)
        })

    except (Game.DoesNotExist, GameState.DoesNotExist):
        return render(request, 'plays/play.html', {
            "play_id": play_id,
            'game_data': None
        })

# 获取玩家颜色的辅助函数
def get_player_color(player_number):
    colors = {
        1: '#ffeb3b',  # 黄色
        2: '#2196F3',  # 蓝色
        3: '#4CAF50',  # 绿色
        4: '#ffffff'  # 白色
    }
    return colors.get(player_number, '#ffeb3b')  # 默认返回黄色
